package com.rickpan.config;

import io.minio.MinioClient;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

/**
 * 存储配置类
 * 根据配置创建相应的存储客户端
 */
@Configuration
public class StorageConfig {
    
    private static final Logger logger = LoggerFactory.getLogger(StorageConfig.class);
    
    @Autowired
    private MinIOProperties minIOProperties;
    
    /**
     * 创建 MinIO 客户端
     * 仅在存储类型为 minio 时创建
     */
    @Bean
    @ConditionalOnProperty(name = "app.storage.type", havingValue = "minio")
    public MinioClient minioClient() {
        try {
            logger.info("初始化 MinIO 客户端: endpoint={}, bucketName={}", 
                       minIOProperties.getEndpoint(), minIOProperties.getBucketName());
            
            // 创建优化的 HTTP 客户端
            OkHttpClient httpClient = createOptimizedHttpClient();
            
            // 创建 MinIO 客户端
            MinioClient client = MinioClient.builder()
                    .endpoint(minIOProperties.getEndpoint())
                    .credentials(minIOProperties.getAccessKey(), minIOProperties.getSecretKey())
                    .region(minIOProperties.getRegion())
                    .httpClient(httpClient)
                    .build();
            
            logger.info("MinIO 客户端初始化成功");
            return client;
            
        } catch (Exception e) {
            logger.error("MinIO 客户端初始化失败", e);
            throw new RuntimeException("MinIO 客户端初始化失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 创建优化的 HTTP 客户端
     */
    private OkHttpClient createOptimizedHttpClient() {
        return new OkHttpClient.Builder()
                // 连接池配置：最大50个连接，保持5分钟
                .connectionPool(new ConnectionPool(50, 5, TimeUnit.MINUTES))
                // 连接超时：10秒
                .connectTimeout(10, TimeUnit.SECONDS)
                // 读取超时：30秒
                .readTimeout(30, TimeUnit.SECONDS)
                // 写入超时：30秒
                .writeTimeout(30, TimeUnit.SECONDS)
                // 启用连接重试
                .retryOnConnectionFailure(true)
                .build();
    }
}
